package com.tg.demo.web;

import com.github.pagehelper.PageInfo;
import com.tg.demo.common.ConstantUtil;
import com.tg.demo.common.Page;
import com.tg.demo.common.Result;
import com.tg.demo.common.util.StringUtils;
import com.tg.demo.config.SysUserContext;
import com.tg.demo.entity.User;
import com.tg.demo.entity.UserVO;
import com.tg.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * IndexController
 *
 * @author yuanjin
 * @date 2019/3/21
 */
@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 登录页面
     *
     * @return String
     */
    @GetMapping("/login")
    public String loginGet() {
        return "/login";
    }

    /**
     * 登录Post请求
     *
     * @return String
     */
    @PostMapping("/login/loginPost")
    @ResponseBody
    public Result loginPost(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        Result result = new Result(0, "失败");
        try {
            String userCode = request.getParameter("userCode");
            String password = request.getParameter("password");
            if (StringUtils.isBlank(userCode) || StringUtils.isBlank(password)) {
                result.setMsg("账号或密码为空！");
                return result;
            }
            User user = User.builder().userCode(userCode).build();
            List<User> list = userService.getUserByCondition(user);
            if (list != null && list.size() > 0) {
                if (!password.equals(list.get(0).getPassword())) {
                    result.setMsg("密码错误！");
                    return result;
                }
            } else {
                result.setMsg("账号错误，请重新登录！");
                return result;
            }
            session.setAttribute(ConstantUtil.SESSION_KEY, userCode);
            session.setMaxInactiveInterval(60 * 60);
            result.setCode(1);
            result.setMsg("登录成功");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setMsg("服务器异常");
            return result;
        }
    }

    /**
     * 退出
     *
     * @return String
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        // 移除session
        HttpSession session = request.getSession();
        session.removeAttribute(ConstantUtil.SESSION_KEY);
        SysUserContext.remove();
        return "redirect:/login";
    }

    /**
     * 跳转到列表页
     *
     * @param model the model
     * @return string string
     */
    @RequestMapping(value = "/gotoListPage", method = {RequestMethod.GET, RequestMethod.POST})
    public String gotoListPage(Model model) {
        return "/user/list";
    }

    /**
     * 跳转到列表页
     *
     * @param model the model
     * @return string string
     */
    @RequestMapping(value = "/gotoTeacherList", method = {RequestMethod.GET, RequestMethod.POST})
    public String gotoTeacherList(Model model) {
        return "/user/teacherList";
    }

    /**
     * 跳转到列表页
     *
     * @param model the model
     * @return string string
     */
    @RequestMapping(value = "/gotoManagerList", method = {RequestMethod.GET, RequestMethod.POST})
    public String gotoManagerList(Model model) {
        return "/user/managerList";
    }

    @RequestMapping("/list")
    @ResponseBody
    public Page list(Page page, User user) {
        PageInfo<User> info = userService.getListByPage(user, page.getPage(), page.getPageSize());
        Page result = new Page();
        result.setTotal(Integer.parseInt(info.getTotal() + ""));
        result.setRows(info.getList());
        return result;
    }

    /**
     * 跳转到用户信息表页面
     *
     * @param userCode the id
     * @return string string
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public Result gotoEdit(String userCode) {
        Result result = new Result(0, "failed");
        User user = new User();
        if (!StringUtils.isBlank(userCode)) {
            List<User> list = userService.getUserByCondition(User.builder().userCode(userCode).build());
            if (!list.isEmpty()) {
                user = list.get(0);
            }
        }
        result.setData(user);
        result.setCode(1);
        return result;
    }

    /**
     * 保存用户信息
     *
     * @param user the user
     * @return object object
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Result save(@ModelAttribute User user) {
        Result result = new Result(ConstantUtil.FAILURE_CODE, ConstantUtil.FAILURE_MESSAGE);
        if (user != null) {
            if (StringUtils.isBlank(user.getUserCode())) {
                String userCode = userService.getNewUserCode();
                user.setUserCode(userCode);
                user.setPassword("123456");
                userService.insert(user);
            } else {
                userService.update(user);
            }
            result = new Result(ConstantUtil.SUCCESS_CODE, ConstantUtil.SUCCESS_MESSAGE);
        }
        return result;
    }

    /**
     * 删除用户信息表数据
     *
     * @param userCode userCode
     * @return Result Result
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Result delete(String userCode) {
        Result result = new Result(ConstantUtil.FAILURE_CODE, ConstantUtil.FAILURE_MESSAGE);
        Long res = userService.delete(userCode);
        if (res > 0) {
            result = new Result(ConstantUtil.SUCCESS_CODE, ConstantUtil.SUCCESS_MESSAGE);
        }
        return result;

    }

    /**
     * 登录页面
     *
     * @return String
     */
    @GetMapping("/login/changePW")
    public String changePW() {
        return "/changePW";
    }

    /**
     * 保存用户信息
     *
     * @param vo the user
     * @return object object
     */
    @RequestMapping(value = "/login/savePW")
    @ResponseBody
    public Result savePW(@ModelAttribute UserVO vo) {
        Result result = new Result(ConstantUtil.FAILURE_CODE, ConstantUtil.FAILURE_MESSAGE);
        if (vo != null) {
            List<User> list = userService.getUserByCondition(User.builder().userCode(vo.getUserCode()).build());
            if (list == null || list.size() != 1) {
                result.setMsg("登录账号错误");
                return result;
            }
            User user = list.get(0);
            if (!vo.getOldPassword().equals(user.getPassword())) {
                result.setMsg("旧密码错误，请重新输入");
                return result;
            }
            user.setPassword(vo.getNewPassword());
            user.setModifyTime(new Date());
            userService.update(user);
            result = new Result(ConstantUtil.SUCCESS_CODE, ConstantUtil.SUCCESS_MESSAGE);
        }
        return result;
    }
}
